package com.atgouwu.scmall.seckill.controller;

import com.atgouwu.scmall.common.utils.R;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("seckill/redisson")
public class RedissonController {

    @Autowired
    private RedissonClient redissonClient; //Redisson分布式锁
    @GetMapping("/distributedLock")
    public R distributedLock(@RequestParam Map<String, Object> params) {
        //Redisson分布式锁
        RLock rlock = redissonClient.getLock("seckill:upload:lock"); //可重入锁
        RReadWriteLock lock = redissonClient.getReadWriteLock("rw-lock"); //读写锁
        RLock rLock = lock.writeLock();
        rLock.lock();
        RLock rLocks = lock.readLock();
        rLocks.lock();
        rLock.unlock();
        try {
            rlock.lock(10, TimeUnit.SECONDS); //加锁10秒
            //业务接口
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rlock.unlock();
        }
        return R.ok().put("data", "res");
    }

}
